import Vue from 'vue'
import VueRouter from 'vue-router'

Vue.use(VueRouter)

const routes = [
  // 一级路由
  { path: '/login', component: () => import('@/views/Login') },
  { path: '/enroll', component: () => import('@/views/enroll') },
  {
    path: '/',
    redirect: '/dashboard',
    component: () => import('@/views/Home'),
    children: [
      { path: 'dashboard', component: () => import('@/views/Home/Dashboard') },
      { path: 'user', component: () => import('@/views/Home/User') },
      { path: 'category', component: () => import('@/views/Home/Category') },
      { path: 'post', component: () => import('@/views/Home/Post') },
      {
        path: 'post/postadd',
        component: () => import('@/views/Home/Post/postAdd'),
      },
      {
        path: 'post/revision',
        component: () => import('@/views/Home/Post/revision'),
      },
      {
        path: 'usermessage',
        component: () => import('@/views/Home/userMessage'),
      },
    ],
  },

  { path: '*', component: () => import('@/views/404') },
]

const router = new VueRouter({
  mode: 'history',
  base: process.env.BASE_URL,
  routes,
})
// 设置导航守卫
// 全局前置导航守卫
router.beforeEach((to, from, next) => {
  // to: 需要访问的path
  // from: 从哪里来
  // next: 放行
  // 定义一个登录的状态
  let token = localStorage.getItem('token')
  if (token) {
    // 已经登录状态
    if (to.path == '/login') {
      next('/home')
    } else {
      next()
    }
  } else {
    // 没有登录的状态只能访问/login页面
    if (to.path == '/login' || to.path == '/enroll') {
      next()
    } else {
      alert('请先登录')
      next('/login')
    }
  }
})

export default router
